package com.yikaiye.android.yikaiye.ui.activity.mine;

import android.os.Bundle;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivitySettingBinding;
import com.yikaiye.android.yikaiye.dialog.DownloadDialog;
import com.yikaiye.android.yikaiye.dialog.LogoutDialog;
import com.yikaiye.android.yikaiye.dialog.MyDialog;
import com.yikaiye.android.yikaiye.ui.activity.DesActivity;
import com.yikaiye.android.yikaiye.ui.activity.viewmodel.MainViewModel;
import com.yikaiye.android.yikaiye.utils.AppUtils;
import com.yikaiye.android.yikaiye.utils.CacheUtils;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.DownLoadHelper;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;

import java.io.File;

/**
 * 设置
 */
public class SettingActivity extends BaseActivity<ActivitySettingBinding, MainViewModel> {

    private LogoutDialog logoutDialog;
    private MyDialog myDialog;
    private String downApkUrl;


    @Override
    protected MainViewModel bindModel() {
        return getViewModel(this, MainViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.setting));
        binding.tvCacheSize.setText(CacheUtils.getTotalCacheSize(context));
        binding.tvVersionCode.setText(getString(R.string.current_version, Constant.VERSION));
        initDialog();
    }

    private void initDialog() {
        logoutDialog = new LogoutDialog(this) {
            @Override
            public void logout() {
                MyApplication.manager.clearUserInfo();
                CommonUtil.jumpToLogin(SettingActivity.this);
                dismissDialog();
            }
        };

        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                dismissDialog();
            }

            @Override
            public void rightClick() {
                dismissDialog();
                downloadApk(downApkUrl);
            }
        };
        myDialog.setText(getString(R.string.version_update), getString(R.string.update_to_last_version_), getString(R.string.cancel_text), getString(R.string.confirm_text));
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.llVersionUpdate, o -> viewModel.checkVersion());
        viewModel.onDelayClick(binding.llClearCache, o -> {
            CacheUtils.clearAllCache(MyApplication.getContext());
            ToastHelper.show(getString(R.string.cache_cleared));
            binding.tvCacheSize.setText(CacheUtils.getTotalCacheSize(context));
        });
        viewModel.onDelayClick(binding.llUserAgreement, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.NAME_KEY, getString(R.string.user_agreement));
            JumpIntent.jump(this, DesActivity.class, bundle);
        });
        viewModel.onDelayClick(binding.llPrivacyPolicy, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.NAME_KEY, getString(R.string.privacy_policy));
            JumpIntent.jump(this, DesActivity.class, bundle);
        });
        viewModel.onDelayClick(binding.tvLogout, o -> logoutDialog.showDialog());

        // 版本更新
        viewModel.versionModelMutableLiveData.observe(this, versionModel -> {
            int currentVersion = Integer.parseInt(AppUtils.getVersionName(context).replace(".", ""));
            int serviceVersion = Integer.parseInt(versionModel.getVersion().replace(".", ""));
            if (currentVersion < serviceVersion) {
                downApkUrl = versionModel.getDownYkyAppUrl();
                myDialog.showDialog();
            } else {
                ToastHelper.show(getString(R.string.already_last_version));
            }
        });
    }

    /**
     * 通过链接下载apk进行更新
     * @param apkUrl apk下载链接
     */
    private void downloadApk(String apkUrl) {
        // 截取apk的名称，如yky.apk
        String destFileName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
        final File filesDir = getExternalFilesDir("upgrade");
        // 如果文件不存在新建一个
        if (filesDir != null) {
            if (!filesDir.exists()) {
                filesDir.mkdirs();
            }

            final String filePath = filesDir.getPath() + "/";
            DownloadDialog downloadDialog = new DownloadDialog(this);
            downloadDialog.showDialog();
            DownLoadHelper.getInstance().download(apkUrl, filePath, new DownLoadHelper.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(String path) {
                    downloadDialog.dismissDialog();
                    if (!XXPermissions.isGrantedPermission(context, Permission.REQUEST_INSTALL_PACKAGES)) {
                        XXPermissions.with(context).permission(Permission.REQUEST_INSTALL_PACKAGES).request((permissions, all) -> CommonUtil.installAPK(context, filePath + destFileName));
                    } else {
                        CommonUtil.installAPK(context, filePath + destFileName);
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    downloadDialog.setProgress(progress);
                }

                @Override
                public void onDownloadFailed() {
                    downloadDialog.dismissDialog();
                }
            });
        }
    }
}